package org.hcf.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

@Slf4j
public class HttpClient {

    public static String post(String url, String content) {
        try {
            RestTemplate restTemplate = new RestTemplate();

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            // 设置请求体数据
//        String requestBody = "{\"name\":\"John\",\"email\":\"john@example.com\"}";
            HttpEntity<String> requestEntity = new HttpEntity<>(content, headers);

            // 发送POST请求
//        String url = "http://unknown-server.com/submit";
            ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);

            // 处理响应
            if (responseEntity.getStatusCode().is2xxSuccessful()) {
                String responseBody = responseEntity.getBody();
                log.info("向[" + url + "]发送数据[" + content + "]成功:" + responseBody);
                return responseBody;
//            System.out.println("数据提交成功：" + responseBody);
            } else {
                log.info("向[" + url + "]发送数据[" + content + "]失败:" + responseEntity.getStatusCode() + "." + responseEntity.getBody());
                return responseEntity.getBody();
//            System.out.println("数据提交失败");
            }
        } catch (Throwable ex) {
            log.error("向[" + url + "]发送数据[" + content + "]异常", ex);
            return null;
        }
    }
}
